package com.csw.shuanfa.GlobalConfig.format;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;

import java.io.IOException;
import java.lang.reflect.Field;

public class ConditionalLongSerializer extends JsonSerializer<Long> implements ContextualSerializer {

    private int maxLength = 10; // 默认阈值

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) {
        if (property != null) {
            try {
                // 获取字段的注解信息
                Field field = (Field) property.getMember().getAnnotated();
                if (field != null) {
                    ConditionalSerialize annotation = field.getAnnotation(ConditionalSerialize.class);
                    if (annotation != null) {
                        maxLength = annotation.maxLength(); // 从注解获取最大长度
                    }
                }
            } catch (Exception e) {
                throw new RuntimeException("获取字段注解失败", e);
            }
        }
        return this;
    }

    @Override
    public void serialize(Long value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (value == null) {
            gen.writeNull(); // 如果值为null，直接写null
            return;
        }

        String strValue = value.toString();
        if (strValue.length() > maxLength) {
            gen.writeNull(); // 如果值的长度超过最大长度，写null
        } else {
            gen.writeString(strValue); // 否则，写字符串形式的值
        }
    }
}